package com.lz.controller;

import com.alibaba.fastjson.JSONObject;
import com.lz.service.LoginService;
import com.lz.utils.AppMD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Created by lz on 2018/5/10.
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 跳回主页
     * @return
     */
    @RequestMapping("")
    public String toIndex(){
        return "redirect:/index.jsp";
    }

    /**
     * 登录方法
     * @param request
     * @return
     */
    @RequestMapping(value = "/in", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject login(HttpServletRequest request){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotBlank(username)){
            if (StringUtils.isNotBlank(password)){
                List<Map<String, Object>> user = loginService.findUser(username);
                if (user.size() > 0){
                    String md5 = AppMD5Util.MD5(password);
                    if (md5.equals(user.get(0).get("password"))){
                        //request.getSession().setAttribute("username",username);
                        jsonObject.put("msg","登录成功！");
                    } else {
                        jsonObject.put("msg","密码不正确！");
                    }
                } else {
                    jsonObject.put("msg","用户不存在，请注册！");
                }
            } else {
                jsonObject.put("msg","密码不能为空！");
            }
        } else {
            jsonObject.put("msg","用户名不能为空！");
        }
        return jsonObject;
    }

    /**
     * 退出
     * @param request
     * @return
     */
    @RequestMapping("/out")
    @ResponseBody
    public JSONObject logout(HttpServletRequest request){
        Object username = request.getSession().getAttribute("username");
        request.getSession().setAttribute("username",null);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", "用户" + username.toString() + "退出");
        return jsonObject;
    }
}
